<template>
  <div class="Box">
    <!-- 顶部搜索 -->
    <div class="SearchBox flex-LAR">
      <el-input v-model="SearchKeyWord.searchValue" placeholder="请输入搜索内容" class="input-with-select">
        <template #prepend>
          <el-select v-model="SearchKeyWord.selectKey" style="width: 6.25rem">
            <el-option label="演练名称" value="drill_name" />
            <el-option label="预案名称" value="plan_name" />
          </el-select>
        </template>
        <template #append>
          <el-button class="searchBtn" :icon="Search" />
        </template>
      </el-input>
      <div>
        <el-button type="success" @click="handleAdd">新增演练</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="TableBox">
      <cy-table class="Table" row-key="drill_id" :data="tableData" :columns="ruleTable.columns" :loading="loading" />
    </div>
    <!-- 分页 -->
    <div class="PageBox">
      <el-pagination :hide-on-single-page="true" v-model:current-page="page.currentPage" v-model:page-size="page.pageSize"
        v-model:total="page.total" />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="演练名称" prop="drill_name">
              <el-input v-model="form.drill_name" placeholder="请输入演练名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联预案" prop="plan_id">
              <el-select v-model="form.plan_id" placeholder="请选择关联预案">
                <el-option v-for="plan in planList" :key="plan.plan_id" :label="plan.plan_name" :value="plan.plan_id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="演练类型" prop="drill_type">
              <el-select v-model="form.drill_type" placeholder="请选择演练类型">
                <el-option v-for="item in drillTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="演练时间" prop="drill_time">
              <el-date-picker v-model="form.drill_time" type="datetime" placeholder="选择日期时间" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsible_person_id">
              <el-select v-model="form.responsible_person_id" placeholder="请选择负责人">
                <el-option v-for="person in personnelList" :key="person.personnel_id" :label="person.name"
                  :value="person.personnel_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参与团队" prop="participating_teams">
              <el-select v-model="form.participating_teams" multiple placeholder="请选择参与团队">
                <el-option v-for="team in teamList" :key="team.team_id" :label="team.team_name" :value="team.team_id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="演练地点" prop="location">
              <el-input v-model="form.location" placeholder="请输入演练地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="演练状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择演练状态">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="演练描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入演练描述" />
        </el-form-item>

        <el-form-item label="演练结果" prop="result">
          <el-input v-model="form.result" type="textarea" :rows="3" placeholder="请输入演练结果" />
        </el-form-item>

        <el-form-item label="发现问题" prop="issues_found">
          <el-input v-model="form.issues_found" type="textarea" :rows="3" placeholder="请输入发现的问题" />
        </el-form-item>

        <el-form-item label="改进建议" prop="improvement_suggestions">
          <el-input v-model="form.improvement_suggestions" type="textarea" :rows="3" placeholder="请输入改进建议" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from "@element-plus/icons-vue";
import CyTable from "@/components/table";

const page = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

const SearchKeyWord = reactive({
  selectKey: "drill_name",
  searchValue: "",
});

const tableData = ref([
  {
    drill_id: 1,
    drill_name: '2023年第一季度地震应急演练',
    plan_id: 1,
    plan_name: '地震应急预案',
    drill_type: 'desktop',
    drill_time: '2023-03-15 09:00:00',
    responsible_person_id: 1,
    responsible_person: '叶致远',
    participating_teams: [1],
    participating_teams_names: '应急救援一队',
    location: '公司总部大楼',
    status: 'completed',
    description: '模拟6.5级地震应急响应流程演练',
    result: '顺利完成所有预设场景，响应时间达标',
    issues_found: '部分通讯设备在模拟地震中信号不稳定',
    improvement_suggestions: '更新通讯设备，增加备用通讯方案',
    created_at: '2023-03-10',
  },
  {
    drill_id: 2,
    drill_name: '疫情防控应急演练',
    plan_id: 2,
    plan_name: '疫情应急预案',
    drill_type: 'functional',
    drill_time: '2023-04-20 14:00:00',
    responsible_person_id: 2,
    responsible_person: '向子韬',
    participating_teams: [2],
    participating_teams_names: '医疗应急队',
    location: '公司医疗中心',
    status: 'completed',
    description: '模拟突发疫情应急处置流程',
    result: '隔离流程执行良好，但物资调配稍慢',
    issues_found: '防护物资储备不足',
    improvement_suggestions: '增加防护物资储备量，建立快速调配机制',
    created_at: '2023-04-15',
  },
  {
    drill_id: 3,
    drill_name: '消防疏散演练',
    plan_id: 3,
    plan_name: '火灾应急预案',
    drill_type: 'full_scale',
    drill_time: '2023-06-10 10:30:00',
    responsible_person_id: 3,
    responsible_person: '金詩涵',
    participating_teams: [1, 2],
    participating_teams_names: '应急救援一队, 医疗应急队',
    location: '公司园区',
    status: 'completed',
    description: '全公司参与的消防疏散演练',
    result: '疏散时间比标准慢2分钟',
    issues_found: '部分员工对疏散路线不熟悉',
    improvement_suggestions: '加强疏散路线培训，增加指示标识',
    created_at: '2023-06-05',
  },
  {
    drill_id: 4,
    drill_name: '网络安全应急演练',
    plan_id: 5,
    plan_name: '网络安全应急预案',
    drill_type: 'desktop',
    drill_time: '2023-07-05 13:00:00',
    responsible_person_id: 2,
    responsible_person: '向子韬',
    participating_teams: [2],
    participating_teams_names: '技术保障队',
    location: 'IT中心',
    status: 'scheduled',
    description: '模拟网络攻击应急响应',
    result: '',
    issues_found: '',
    improvement_suggestions: '',
    created_at: '2023-06-28',
  },
  {
    drill_id: 5,
    drill_name: '防洪应急演练',
    plan_id: 4,
    plan_name: '洪水应急预案',
    drill_type: 'functional',
    drill_time: '2023-05-20 09:00:00',
    responsible_person_id: 1,
    responsible_person: '叶致远',
    participating_teams: [1],
    participating_teams_names: '应急救援一队',
    location: '公司低洼区域',
    status: 'completed',
    description: '模拟暴雨导致的内涝应急处理',
    result: '沙袋堆放速度达标，排水设备运转良好',
    issues_found: '部分排水设备老化',
    improvement_suggestions: '更新排水设备，增加临时排水泵',
    created_at: '2023-05-15',
  }
]);

const planList = ref([
  { plan_id: 1, plan_name: '地震应急预案' },
  { plan_id: 2, plan_name: '疫情应急预案' },
  { plan_id: 3, plan_name: '火灾应急预案' },
  { plan_id: 4, plan_name: '洪水应急预案' },
  { plan_id: 5, plan_name: '网络安全应急预案' },
]);

const ruleTable = reactive({
  columns: [
    { prop: "drill_id", label: "演练ID" },
    { prop: "drill_name", label: "演练名称" },
    { prop: "plan_name", label: "关联预案" },
    {
      prop: "drill_type", label: "演练类型",
      render: ({ row }) => (
        <el-tag type={getDrillTypeTag(row.drill_type)}>
          {getDrillTypeName(row.drill_type)}
        </el-tag>
      ),
    },
    { prop: "drill_time", label: "演练时间" },
    { prop: "responsible_person", label: "负责人" },
    { prop: "participating_teams_names", label: "参与团队" },
    {
      prop: "status", label: "状态",
      render: ({ row }) => (
        <el-tag type={getStatusTag(row.status)}>
          {getStatusName(row.status)}
        </el-tag>
      ),
    },
    { prop: "location", label: "演练地点" },
    {
      label: "操作",
      align: "center",
      width:250,
      render: ({ row }) => (
        <div>
          <el-button>查看</el-button>
          <el-button type="primary">编辑</el-button>
          <el-button type="danger">删除</el-button>
        </div>
      ),
    },
  ],
});

const personnelList = ref([
  { personnel_id: 1, name: '叶致远' },
  { personnel_id: 2, name: '向子韬' },
  { personnel_id: 3, name: '金詩涵' },
  { personnel_id: 4, name: '蒋嘉伦' },
]);

const teamList = ref([
  { team_id: 1, team_name: '应急救援一队' },
  { team_id: 2, team_name: '医疗应急队' },
  { team_id: 3, team_name: '技术保障队' }
]);

const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);

const form = reactive({
  drill_id: '',
  drill_name: '',
  plan_id: '',
  drill_type: '',
  drill_time: '',
  responsible_person_id: '',
  participating_teams: [],
  location: '',
  status: '',
  description: '',
  result: '',
  issues_found: '',
  improvement_suggestions: ''
});

const rules = reactive({
  drill_name: [{ required: true, message: '请输入演练名称', trigger: 'blur' }],
  plan_id: [{ required: true, message: '请选择关联预案', trigger: 'change' }],
  drill_type: [{ required: true, message: '请选择演练类型', trigger: 'change' }],
  drill_time: [{ required: true, message: '请选择演练时间', trigger: 'change' }],
  responsible_person_id: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  status: [{ required: true, message: '请选择演练状态', trigger: 'change' }],
});

const drillTypeOptions = ref([
  { value: 'desktop', label: '桌面演练' },
  { value: 'functional', label: '功能演练' },
  { value: 'full_scale', label: '全面演练' }
]);

const statusOptions = ref([
  { value: 'scheduled', label: '已计划' },
  { value: 'in_progress', label: '进行中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' }
]);

const getDrillTypeName = (type) => {
  const item = drillTypeOptions.value.find(item => item.value === type);
  return item ? item.label : '未知';
};

const getDrillTypeTag = (type) => {
  const map = {
    desktop: '',
    functional: 'info',
    full_scale: 'success'
  };
  return map[type] || '';
};

const getStatusName = (status) => {
  const item = statusOptions.value.find(item => item.value === status);
  return item ? item.label : '未知';
};

const getStatusTag = (status) => {
  const map = {
    scheduled: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  };
  return map[status] || '';
};

const handleAdd = () => {
  dialogTitle.value = '新增演练记录';
  formRef.value?.resetFields();
  dialogVisible.value = true;
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.drill_id) {
        const index = tableData.value.findIndex(item => item.drill_id === form.drill_id);
        if (index !== -1) {
          tableData.value[index] = { 
            ...form,
            responsible_person: getPersonnelName(form.responsible_person_id),
            participating_teams_names: getTeamNames(form.participating_teams),
            plan_name: getPlanName(form.plan_id)
          };
          ElMessage.success('编辑成功');
        }
      } else {
        form.drill_id = tableData.value.length + 1;
        tableData.value.push({ 
          ...form,
          responsible_person: getPersonnelName(form.responsible_person_id),
          participating_teams_names: getTeamNames(form.participating_teams),
          plan_name: getPlanName(form.plan_id),
          created_at: new Date().toISOString().split('T')[0]
        });
        ElMessage.success('新增成功');
      }
      dialogVisible.value = false;
    } else {
      ElMessage.error('表单验证失败');
    }
  });
};

const getPersonnelName = (id) => {
  const item = personnelList.value.find(item => item.personnel_id === id);
  return item ? item.name : '未知';
};

const getTeamNames = (ids) => {
  return ids.map(id => {
    const team = teamList.value.find(team => team.team_id === id);
    return team ? team.team_name : '未知';
  }).join(', ');
};

const getPlanName = (id) => {
  const plan = planList.value.find(plan => plan.plan_id === id);
  return plan ? plan.plan_name : '未知';
};
</script>

<style scoped lang="scss">
.Box {
  position: relative;

  .SearchBox {
    width: 100%;
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    .el-input {
      width: 350px;
      margin-left: 0.5rem;
    }

    .searchBtn {
      color: rgb(15, 153, 245);
    }

    .addBtn {
      margin-right: 1rem;
    }
  }

  .PageBox {
    background-color: #fff;
    padding-left: 30%;
    margin: 1rem;
  }

  .TableBox {
    .Table {
      width: 100%;
      min-height: 25rem;
      border-top: 1px solid #eee;
    }
  }

  .EditForm {
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: center;
      align-content: center;
    }
  }
}
</style>